package com.example.yyh.recorddemo.activity;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;

import com.example.yyh.recorddemo.R;
import com.example.yyh.recorddemo.adapter.RecordListAdapter;
import com.example.yyh.recorddemo.base.BaseActivity;
import com.example.yyh.recorddemo.bean.SoundBean;
import com.example.yyh.recorddemo.databinding.ActivityRecordListBinding;
import com.example.yyh.recorddemo.manager.RecordDbManager;
import com.example.yyh.recorddemo.popupwindow.CustomActionSheet;
import com.example.yyh.recorddemo.utils.DateUtils;
import com.example.yyh.recorddemo.utils.FileUtils;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.List;

public class RecordListActivity extends BaseActivity<ActivityRecordListBinding> {

    //查找数据
    private final int QUERY_DATA = 1;

    //删除数据
    private final int DELETE_DATA = 2;

    //播放录音
    private final int PLAY = 3;

    //跳转页面
    private final String SOUND_BEAN = "SOUND_BEAN";

    //数据装载器
    private RecordListAdapter mAdapter;

    //播放器
    private MediaPlayer mMediaPlayer;

    //播放的位置
    private int mPosition = -1;

    /**
     * 处理Handler内存泄漏
     */
    private WeakHandler mHandler;

    private static class WeakHandler extends Handler {
        private WeakReference<RecordListActivity> mActivity;

        public WeakHandler(RecordListActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            RecordListActivity activity = mActivity.get();
            switch (msg.what) {//通知主线程更新UI，这里用常量编译通不过
                case 1://读取数据
                    List<SoundBean> allSoundInfo = (List<SoundBean>) msg.getData().getSerializable(activity.SOUND_BEAN);
                    Log.e("debug", "数据大小--->" + allSoundInfo.size());
                    activity.mAdapter.update(allSoundInfo);
                    break;
                case 2://删除数据
                    int position = msg.arg1;
                    activity.mAdapter.remove(position);
                    activity.mAdapter.notifyDataSetChanged();
                    break;
                case 3://播放录音
                    if (activity.mMediaPlayer != null) {
                        int currentPosition = activity.mMediaPlayer.getCurrentPosition();
                        int duration = activity.mMediaPlayer.getDuration();
                        if (currentPosition >= duration && !activity.mMediaPlayer.isLooping()) {
                            removeMessages(3);
                            activity.mContentBindingView.seekbar.setProgress(0);
                            activity.mContentBindingView.play.setImageResource(R.mipmap.icon_play);
                        } else {
                            sendEmptyMessage(3);
                        }
                        activity.mContentBindingView.seekbar.setProgress(currentPosition);
                        String currentTime = DateUtils.getMSTime(currentPosition);
                        String durationTime = DateUtils.getMSTime(duration);
                        activity.mContentBindingView.time.setText(activity.getString(R.string.play_time, currentTime, durationTime));
                    }
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_list);
    }

    @Override
    protected void initData() {
        mHandler = new WeakHandler(this);
        mAdapter = new RecordListAdapter(this);
        mContentBindingView.listview.setAdapter(mAdapter);

        //在子线程读取数据库
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<SoundBean> allSoundInfo = RecordDbManager.getInstance().getAllSoundInfo();
                Message message = new Message();
                message.what = QUERY_DATA;
                message.obj = allSoundInfo;
                Bundle bundle = new Bundle();
                bundle.putSerializable(SOUND_BEAN, (Serializable) allSoundInfo);
                message.setData(bundle);
                mHandler.sendMessage(message);
            }
        }).start();
    }

    @Override
    protected void setListener() {
        mContentBindingView.setOnClick(this);
        //设置列表接口回调
        mAdapter.setListener(new RecordListAdapter.OnClickListener() {

            //点击播放
            @Override
            public void play(SoundBean soundBean, int position) {
                Log.e("debug", "position-->" + position);
                if (mPosition != position) {//判断点击这个录音是否在播放，如果没有就播放，如果有就没反应
                    mContentBindingView.setIsPlay(true);
                    mContentBindingView.setSoundBean(soundBean);
                    mPosition = position;
                    initMediaPlay(soundBean.getFilePath());
                }
            }

            //点击弹出选择窗，目前只有删除功能
            @Override
            public void more(SoundBean soundBean, int position) {
                showMoreDialog(soundBean, position);
            }
        });
        //设置seekbar滑动
        mContentBindingView.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                    mMediaPlayer.seekTo(seekBar.getProgress());
                }
            }
        });
    }

    /**
     * 点击更多出来弹窗，现在只写了删除
     *
     * @param soundBean
     */
    private void showMoreDialog(final SoundBean soundBean, final int position) {
        CustomActionSheet sheet = CustomActionSheet.getInstance(this);
        String[] stringItems = new String[]{getString(R.string.delete)};
        sheet.setItems(stringItems);
        sheet.show();
        sheet.setListener(new CustomActionSheet.PupopListener() {
            @Override
            public void onItemClicked(int index, String item) {
                switch (index) {
                    case 0:
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                RecordDbManager.getInstance().deleteById(soundBean.getId());
                                FileUtils.deleteFile(new File(soundBean.getFilePath()));
                                Message message = new Message();
                                message.what = DELETE_DATA;
                                message.arg1 = position;
                                mHandler.sendMessage(message);
                            }
                        }).start();
                        break;
                }
            }
        });
    }

    /**
     * 初始化MediaPlay播放器,这里可以不用封装，因为需要Handler更新进度
     *
     * @param filePath
     */
    private void initMediaPlay(String filePath) {
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
        }

        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mContentBindingView.seekbar.setProgress(0);
                mContentBindingView.play.setImageResource(R.mipmap.icon_play);
            }
        });

        try {
            mMediaPlayer.reset();
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setDataSource(filePath);
            mMediaPlayer.prepare();
            mContentBindingView.seekbar.setMax(mMediaPlayer.getDuration());
            mMediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mHandler.sendEmptyMessage(3);
        mContentBindingView.play.setImageResource(R.mipmap.icon_pause);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.play:
                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.pause();
                    mContentBindingView.play.setImageResource(R.mipmap.icon_play);
                } else {
                    mMediaPlayer.start();
                    mContentBindingView.play.setImageResource(R.mipmap.icon_pause);
                }
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        releaseMedia();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseMedia();
    }


    /**
     * 释放掉MediaPlay，避免内存泄漏和一直在后台播放
     */
    private void releaseMedia() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
        mHandler.removeCallbacksAndMessages(null);
    }

    public static void show(Context context) {
        context.startActivity(new Intent(context, RecordListActivity.class));
    }
}
